import SPI;
import Credential;
import Util;
import OpenApiUtil;
import EndpointUtil;
import EncodeUtil;
import SignatureUtil;
import String;
import Map;
import Array;

extends SPI;

init() {
  super();
}

async function modifyConfiguration(context: SPI.InterceptorContext, attributeMap: SPI.AttributeMap): void {
  var request = context.request;
  var config = context.configuration;
  config.endpoint = getEndpoint(request.productId, config.regionId, config.endpointRule, config.network, config.suffix, config.endpointMap, config.endpoint);

}

async function modifyRequest(context: SPI.InterceptorContext, attributeMap: SPI.AttributeMap): void {
  var request = context.request;
  var config = context.configuration;
  request.headers = {
    date = Util.getDateUTCString(),
    host = config.endpoint,
    x-acs-version = request.version,
    x-acs-action = request.action,
    user-agent = request.userAgent,
    x-acs-signature-nonce = Util.getNonce(),
    x-acs-signature-method = 'HMAC-SHA1',
    x-acs-signature-version = '1.0',
    accept = 'application/json',
    ...request.headers
  };

  if (!Util.isUnset(request.stream)) {
    var tmp = Util.readAsBytes(request.stream);
    request.stream = tmp;
    request.headers.content-type = 'application/octet-stream';
  } else {
    if (!Util.isUnset(request.body)) {
      if (Util.equalString(request.reqBodyType, 'json')) {
        var jsonObj = Util.toJSONString(request.body);
        request.stream = jsonObj;
        request.headers.content-type = 'application/json; charset=utf-8';
      } else {
        var m = Util.assertAsMap(request.body);
        var formObj = OpenApiUtil.toForm(m);
        request.stream = formObj;
        request.headers.content-type = 'application/x-www-form-urlencoded';
      }
    }
  }

  if (!Util.equalString(request.authType, 'Anonymous')) {
    var credential : Credential = request.credential;
    var accessKeyId = credential.getAccessKeyId();
    var accessKeySecret = credential.getAccessKeySecret();
    var securityToken = credential.getSecurityToken();
    var bearerToken = credential.getBearerToken();
    if (!Util.empty(bearerToken)) {
        request.headers.x-acs-bearer-token = bearerToken;
        request.headers.Authorization = `Bearer ${bearerToken}`;
    } else {
        if (!Util.empty(securityToken)) {
          request.headers.x-acs-security-token = securityToken;
        }
        request.headers.Authorization = getAuthorization(request.pathname, request.method, request.query, request.headers, accessKeyId, accessKeySecret);
    }
  }
}

async function modifyResponse(context: SPI.InterceptorContext, attributeMap: SPI.AttributeMap): void {
  var request = context.request;
  var response = context.response;
  if (Util.is4xx(response.statusCode) || Util.is5xx(response.statusCode)) {
    var _res = Util.readAsJSON(response.body);
    var err = Util.assertAsMap(_res);
    var requestId = defaultAny(err.RequestId, err.requestId);
    throw {
      code = `${defaultAny(err.Code, err.code)}`,
      message = `code: ${response.statusCode}, ${defaultAny(err.Message, err.message)} request id: ${requestId}`,
      data = err,
    };
  }
  if (Util.equalString(request.bodyType, 'binary')) {
    response.deserializedBody = response.body;
  } else if (Util.equalString(request.bodyType, 'byte')) {
    var byt = Util.readAsBytes(response.body);
    response.deserializedBody = byt;
  } else if (Util.equalString(request.bodyType, 'string')) {
    var str = Util.readAsString(response.body);
    response.deserializedBody = str;
  } else if (Util.equalString(request.bodyType, 'json')) {
    var obj = Util.readAsJSON(response.body);
    var res = Util.assertAsMap(obj);
    response.deserializedBody = res;
  } else if (Util.equalString(request.bodyType, 'array')) {
    var arr = Util.readAsJSON(response.body);
    response.deserializedBody = arr;
  } else {
    response.deserializedBody = Util.readAsString(response.body);
  }
}

function getEndpoint(productId: string, regionId: string, endpointRule: string, network: string, suffix: string, endpointMap: map[string]string, endpoint: string) throws: string{
  if (!Util.empty(endpoint)) {
    return endpoint;
  }

  if (!Util.isUnset(endpointMap) && !Util.empty(endpointMap[regionId])) {
    return endpointMap[regionId];
  }
  return EndpointUtil.getEndpointRules(productId, regionId, endpointRule, network, suffix);
}

function defaultAny(inputValue: any, defaultValue: any): any {
  if (Util.isUnset(inputValue)) {
    return defaultValue;
  }
  return inputValue;
}

async function getAuthorization(pathname: string, method: string, query: map[string]string, headers: map[string]string, ak: string, secret: string): string {
  var signature = getSignature(pathname, method, query, headers, secret);
  return `acs ${ak}:${signature}`;
}

async function getSignature(pathname: string, method: string, query: map[string]string, headers: map[string]string, secret: string): string {
  var stringToSign : string = '';
  var canonicalizedResource = buildCanonicalizedResource(pathname, query);
  var canonicalizedHeaders = buildCanonicalizedHeaders(headers);
  stringToSign = `${method}\n${canonicalizedHeaders}${canonicalizedResource}`;
  var signature = SignatureUtil.HmacSHA1Sign(stringToSign, secret);
  return EncodeUtil.base64EncodeToString(signature);
}

async function buildCanonicalizedResource(pathname: string, query: map[string]string): string {
  var canonicalizedResource : string = pathname;
  if (!Util.isUnset(query)) {
    var queryArray : [string] = Map.keySet(query);
    var sortedQueryArray = Array.ascSort(queryArray);
    var separator : string = '?';
    for(var key : sortedQueryArray) {
      canonicalizedResource = `${canonicalizedResource}${separator}${key}`;
      if (!Util.empty(query[key])) {
        canonicalizedResource = `${canonicalizedResource}=${query[key]}`;
      }
      separator = '&';
    }
  }
  return canonicalizedResource;
}

async function buildCanonicalizedHeaders(headers: map[string]string): string {
  var accept = headers.accept;
  if (Util.isUnset(accept)) {
    accept = '';
  }
  var contentMd5 = headers.content-md5;
  if (Util.isUnset(contentMd5)) {
    contentMd5 = '';
  }
  var contentType = headers.content-type;
  if (Util.isUnset(contentType)) {
    contentType = '';
  }
  var date = headers.date;
  if (Util.isUnset(date)) {
    date = '';
  }
  var canonicalizedHeaders : string = `${accept}\n${contentMd5}\n${contentType}\n${date}\n`;
  var sortedHeaders : [string] = getSignedHeaders(headers);
  for(var header : sortedHeaders) {
    var value = headers[header];
    var valueTrim = String.trim(value);
    canonicalizedHeaders = `${canonicalizedHeaders}${header}:${valueTrim}\n`;
  }
  return canonicalizedHeaders;
}

async function getSignedHeaders(headers: map[string]string): [string] {
  var headersArray : [string] = Map.keySet(headers);
  var sortedHeadersArray = Array.ascSort(headersArray);
  var tmp : string = '';
  var separator : string = '';
  for(var key : sortedHeadersArray) {
    var lowerKey = String.toLower(key);
    if (String.hasPrefix(lowerKey, 'x-acs-')) {
      if (!String.contains(tmp, lowerKey)) {
        tmp = `${tmp}${separator}${lowerKey}`;
        separator = ';';
      }
    }
  }
  return String.split(tmp, ';', 0);
}